package store_data_to_redis

import (
	"fmt"
	"github.com/go-redis/redis"
	jsoniter "github.com/json-iterator/go"
	"time"
)

const (
	userRedisKeyFmt = "user:%v" // user:(id)
	userRedisTTL    = time.Hour
)

func StoreUsersToRedis(users []map[string]interface{}) error {

	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	pipe := client.Pipeline()

	for _, userMp := range users {
		currVal, errMarshal := jsoniter.MarshalToString(userMp)
		if errMarshal != nil {
			return errMarshal
		}
		currId, ok := userMp["id"]
		if !ok {
			fmt.Println("这个map不带id: ", userMp)
			continue
		}
		currKey := fmt.Sprintf(userRedisKeyFmt, currId)
		pipe.Set(currKey, currVal, userRedisTTL)
	}

	_, errExec := pipe.Exec()
	if errExec != nil {
		return errExec
	}

	return nil
}
